package io.github.libkodi.basic_gateway.router;

import java.lang.reflect.Method;

import io.github.libkodi.basic_gateway.context.Context;
import io.vertx.core.Handler;
import io.vertx.ext.web.RoutingContext;

public class RouteHandler implements Handler<RoutingContext> {
	private Context ctx;
	private RouteIntercepterImpl interecpter;
	private Object instance;
	private Method method;

	public RouteHandler(Context context, RouteIntercepterImpl intercepter, Object instance,
			Method method) {
		this.ctx = context;
		this.interecpter = intercepter;
		this.instance = instance;
		this.method = method;
	}

	@Override
	public void handle(RoutingContext context) {
		try {
			context.addEndHandler(ar -> {
				ctx.getCurrentThread().release();
			});
			
			interecpter.check(context, method).onSuccess(v -> {
				if (!context.response().ended()) {
					try {
						if (method.getParameterCount() > 0) {
							method.invoke(instance, context);
						} else {
							method.invoke(context);
						}
					} catch (Exception e) {
						context.fail(e);
					}
				}
			}).onFailure(context::fail);
		} catch (Exception e) {
			context.fail(e);
		}
	}

}
